package com.gpjcjl.http;

import android.content.Intent;

import androidx.annotation.NonNull;

import com.base.lib.Logs;
import com.base.lib.SharedHelper;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by biao.yin on 2018/4/26.
 * 网络请求拦截器，拦截token失效
 * 使用方式new OkHttpClient.Builder().addInterceptor(new HttpLogInterceptor())
 *
 * @author yinbiao
 */

public class HttpTokenInterceptor implements Interceptor {

    private static final String TAG = "HttpLogInterceptor";

    @Override
    @NonNull
    public Response intercept(@NonNull Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        //不能直接使用response.body（）.string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，
        // 我们需要创建出一个新的response给应用层处理
//        ResponseBody body = response.body();
//        if (body != null) {
//            这里body.contentLength()有可能为-1，需要特殊处理
//            ResponseBody rb = response.peekBody(body.contentLength() > 0 ? body.contentLength() : Integer.MAX_VALUE);
//            String result = rb.string();
//            if (result.contains("\"code\":1024")) {
//                Logs.d(TAG, "response:" + rb.string());
//                SharedHelper.getInstance().put(Constants.KEY_APPTOKEN, null);
//                if (!App.getInstance().getTopContext().isFinishing() && !App.getInstance().isLoginTop()) {
//                    Intent it = new Intent(App.getInstance().getTopContext(), LoginActivity.class);
//                    it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    App.getInstance().getTopContext().startActivity(it);
//                    return response;
//                }
//            }
//        }
        if (!response.isSuccessful()) {
            Logs.d(TAG, "HttpException:" + response.code() + "：" + response.message());
//            if (response.code() == 401) {
//                SharedHelper.getInstance().put(Constants.KEY_APPTOKEN, null);
//                if (!App.getInstance().getTopContext().isFinishing() && !App.getInstance().isLoginTop()) {
//                    Intent it = new Intent(App.getInstance().getTopContext(), LoginActivity.class);
//                    it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    App.getInstance().getTopContext().startActivity(it);
//                    return response;
//                }
//            }
        }
        return response;
    }
}
